﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using ByteSite.Common;
using System.Linq.Expressions;

namespace ByteSite.BLL
{
    /// <summary>
    ///站点管理
    /// </summary>
    public partial class sites
    {
        private readonly Entitys.sysconfig sysConfig = new BLL.sysconfig().loadConfig();//获得系统配置信息
        private readonly DAL.Data data;

        public sites()
        {
            data = new DAL.Data();
        }

        #region 基本方法================================
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int id)
        {
            return data.Exists<Entitys.dt_sites>(id);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Entitys.dt_sites model)
        {
            try
            {
                data.BeginTran();
                model.id = data.Insert(model);
                if (model.parent_id == 0) 
                {
                    Entitys.dt_navigation parentNavModel = data.Get<Entitys.dt_navigation>(x => x.name == "sys_contents");
                    if (parentNavModel == null)
                    {
                        return 0;
                    }
                    int parent_id = parentNavModel.id;
                    new DAL.navigation().Add("sys_contents", "channel_" + model.build_path, model.title, "", Utils.ObjToInt(model.sort_id), 0, "Show");


                }

                data.CommitTran();

            }
            catch
            {
                data.RollbackTran();
                return 0;
            }
            return model.id;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Entitys.dt_sites model)
        {
            string old_build_path = data.Get<Entitys.dt_sites>(model.id).build_path;
            if (string.IsNullOrEmpty(old_build_path))
            {
                return false;
            }
            if (Update(model, old_build_path))
            {
                if (old_build_path.ToLower() != model.build_path.ToLower())
                {
                    //更改频道分类对应的目录名称
                    FileHelper.MoveDirectory(sysConfig.webpath + DTKeys.DIRECTORY_REWRITE_ASPX + "/" + old_build_path,
                        sysConfig.webpath + DTKeys.DIRECTORY_REWRITE_ASPX + "/" + model.build_path);
                    FileHelper.MoveDirectory(sysConfig.webpath + DTKeys.DIRECTORY_REWRITE_HTML + "/" + old_build_path,
                        sysConfig.webpath + DTKeys.DIRECTORY_REWRITE_HTML + "/" + model.build_path);
                }
                return true;
            }
            return false;
        }
        private bool Update(Entitys.dt_sites model, string oldBuildPath)
        {
            try
            {
                data.BeginTran();

                data.Update<Entitys.dt_sites>(model);

                //检查旧导航是否存在
                if (data.Get<Entitys.dt_navigation>(x=>x.name== "channel_" + oldBuildPath) != null)
                {
                    //如果非基于其它站点数据则修改导航菜单，是则删除旧导航
                    if (model.parent_id == 0)
                    {
                        Entitys.dt_navigation navModel = new Entitys.dt_navigation();
                        data.UpdateColumns<Entitys.dt_navigation>(x => new Entitys.dt_navigation() { name = "channel_" + model.build_path, title = model.title, sort_id = model.sort_id }, x => x.name == "channel_" + oldBuildPath);
                    }
                    else
                    {
                        data.Delete<Entitys.dt_navigation>(x => x.name == "channel_" + oldBuildPath);
                    }
                }
                else if (model.parent_id == 0) //没有旧菜单而非基于其它站点数据需要添加新导航菜单
                {
                    Entitys.dt_navigation parentNavModel = data.Get<Entitys.dt_navigation>(x => x.name == "sys_contents");
                    if (parentNavModel != null)
                    {
                        //修改导航菜单
                        //new DAL.navigation().Update("channel_" + oldBuildPath, "channel_" + model.build_path, model.title, Utils.ObjToInt(model.sort_id));
                    }
                }


                data.CommitTran();
            }
            catch (Exception ex)
            {
                data.RollbackTran();
                return false;
            }
            return true;
            
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int id)
        {
            string build_path = GetBuildPath(id);
            if (string.IsNullOrEmpty(build_path))
            {
                return false;
            }
            data.Delete<Entitys.dt_sites>(id);

            return true;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Entitys.dt_sites GetModel(int id)
        {
            return data.Get<Entitys.dt_sites>(id);
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public List<Entitys.dt_sites> GetList(int top, Expression<Func<Entitys.dt_sites, bool>> whereExpression, Expression<Func<Entitys.dt_sites, object>> orderExpression)
        {
            return data.List<Entitys.dt_sites>(top, whereExpression, orderExpression);
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        public List<Entitys.dt_sites> GetList(int pageSize, int pageIndex, Expression<Func<Entitys.dt_sites, bool>> whereExpression, Expression<Func<Entitys.dt_sites, object>> orderExpression, out int recordCount)
        {
            return data.List<Entitys.dt_sites>(pageSize, pageIndex, whereExpression, orderExpression, out recordCount);
        }
        #endregion

        #region 扩展方法================================
        /// <summary>
        /// 查询生成目录名是否存在
        /// </summary>
        public bool Exists(string build_path)
        {
            //与站点目录下的一级文件夹是否重名
            if (DirPathExists(sysConfig.webpath, build_path))
            {
                return true;
            }
            //与站点aspx目录下的一级文件夹是否重名
            if (DirPathExists(sysConfig.webpath + "/" + DTKeys.DIRECTORY_REWRITE_ASPX + "/", build_path))
            {
                return true;
            }
            //与频道名称是否重名
            if (data.Exists<Entitys.dt_site_channel>(x=>x.name==build_path))
            {
                return true;
            }
            //与其它站点目录是否重名
            if (data.Exists<Entitys.dt_sites>(x=>x.build_path==build_path))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Entitys.dt_sites GetModel(string build_path)
        {
            return data.Get<Entitys.dt_sites>(x => x.build_path == build_path);
        }

        /// <summary>
        /// 返回站点名称
        /// </summary>
        public string GetTitle(int id)
        {
            Entitys.dt_sites model = data.Get<Entitys.dt_sites>(id);
            if (model == null)
                return "";
            else
                return model.title;
        }

        /// <summary>
        /// 返回站点名称
        /// </summary>
        public string GetTitle(string build_path)
        {
            return data.Get<Entitys.dt_sites>(x => x.build_path == build_path).title;
        }

        /// <summary>
        /// 返回站点的生成目录名
        /// </summary>
        public string GetBuildPath(int id)
        {
            Entitys.dt_sites model = data.Get<Entitys.dt_sites>(id);
            if (model == null)
                return "";
            else
                return model.build_path;
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(int id, string strValue)
        {
            return data.UpdateColumns<Entitys.dt_sites>(x => x.templet_path == strValue, x => x.id == id);
        }

        /// <summary>
        /// 保存排序
        /// </summary>
        public bool UpdateSort(int id, int sort_id)
        {

            //取得站点的目录名
            string build_path = data.Get<Entitys.dt_sites>(x => x.id == id).build_path;
            if (build_path == string.Empty)
            {
                return false;
            }

            return data.UpdateColumns<Entitys.dt_sites>(x => x.sort_id == sort_id, x => x.id == id);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Entitys.dt_sites> GetModelList()
        {
            return data.List<Entitys.dt_sites>("", "sort_id asc,id desc");
        }
        #endregion

        #region 私有方法================================

        /// <summary>
        /// 检查生成目录名与指定路径下的一级目录是否同名
        /// </summary>
        /// <param name="dirPath">指定的路径</param>
        /// <param name="build_path">生成目录名</param>
        /// <returns>bool</returns>
        private bool DirPathExists(string dirPath, string build_path)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(Utils.GetMapPath(dirPath));
            foreach (DirectoryInfo dir in dirInfo.GetDirectories())
            {
                if (build_path.ToLower() == dir.Name.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
    }
}